<template>
  <div>
    <header class="header">
      <el-input  placeholder=""  v-model="titleValue" placeholder="" class="top-input"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="add">添加</el-button>
    </header>
    <div class="body">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        max-height="600"
        border
        fit
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed></el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="id"
          label="ID"
          width="50">
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          prop="status"
          label="是否发布"
          width="100">
          <template slot-scope="scope">
            {{scope.row.status==1?'已发布':'未发布'}}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="title"
          label="标题"
          width="300">
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          prop="content"
          label="内容"
          width="">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="rel_time_text"
          label="发布时间"
          width="160">
        </el-table-column>

        <el-table-column
          show-overflow-tooltip
          label="操作"
          width="250">
          <template slot-scope="scope">
            <el-button @click="set(scope.row)"  size="mini">编辑</el-button>
            <el-button @click="deleteBtn(scope.row)"  size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 60,]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :before-close="CloseDialog">
      <div>
        <el-form label-position="right" :rules="rules" label-width="80px" :model="formLabelAlign" ref="formLabelAlign">
          <el-form-item label="标题" prop="title" class="formItem">
            <el-input v-model="formLabelAlign.title"></el-input>
          </el-form-item>
          <el-form-item label="内容" prop="content" class="formItem">
            <el-input v-model="formLabelAlign.content" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="是否发布" prop="status" class="formItem">
            <el-radio v-model="formLabelAlign.status" :label="0">不发布</el-radio>
            <el-radio v-model="formLabelAlign.status" :label="1">发布</el-radio>
          </el-form-item>
          <el-form-item label="发布时间" prop="rel_time" class="formItem">
            <el-date-picker
              v-model="rel_time"
              type="datetime"
              default-time="12:00:00"
              @change="timeChange"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" v-if="dialogTitle!='查看'">
        <el-button class="btn" @click="closeVisible">取 消</el-button>
        <el-button class="btn" type="primary" @click="save('formLabelAlign')" >保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {notice_list, notice_add, notice_del,notice_up} from '../../../utils/api'
export default {
  name: "announcementList",
  data(){
    return{
      dialogTitle:'发布公告',
      dialogVisible:false,
      currentPage: 1,
      total:0,
      limit:10,
      loading:false,
      tableData:[],
      token:sessionStorage.getItem('token'),
      titleValue:'',
      formLabelAlign:{
        title:'',
        content:'',
        status:0,
        rel_time:'',
      },
      rel_time:'',
      rules:{
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 3,  message: '最少5个字符', trigger: 'blur' }
        ],
        rel_time: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写公告内容', trigger: 'blur' }
        ]
      },
    }
  },
  methods:{
    timeChange(e){
      console.log(this.rel_time)
      let time  =  this.getNowTime(e)
      this.formLabelAlign.rel_time =time
    },
    // 编辑
    set(row){
      let obj = JSON.parse(JSON.stringify(row))
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.formLabelAlign = obj
      // this.formLabelAlign.title = obj.title
      // this.formLabelAlign.content = obj.content
      this.rel_time = new Date(obj.rel_time*1000)
      this.formLabelAlign.rel_time = this.getNowTime(obj.rel_time*1000)
    },
    // 删除
    deleteBtn(row){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        notice_del(this.token,row.id).then(res=>{
          if(res.data.status){
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.notice_list()
          }else{
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(e){},
    add(){
      this.dialogTitle = '发布公告'
      this.dialogVisible = true
      this.formLabelAlign = {
          title:' ',
          content:' ',
          status:0,
          rel_time:'',
      }
      this.rel_time = ''
      setTimeout(()=>{
        this.$refs['formLabelAlign'].resetFields();
      },800)
    },
    CloseDialog(){
      this.dialogVisible = false
    },
    closeVisible(){
      this.dialogVisible = false
    },
    save(formName){
      console.log(this.formLabelAlign)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.dialogTitle)
          if(this.dialogTitle == '编辑'){
            console.log(this.formLabelAlign)
            notice_up(this.token,this.formLabelAlign.id,this.formLabelAlign.title,this.formLabelAlign.content,this.formLabelAlign.status,this.formLabelAlign.rel_time).then(res=>{
              if(res.data.status){
                this.$message({
                  message:'编辑成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.notice_list()
              }else{
                this.$message.error(res.data.msg)
              }
            })
          }
        if(this.dialogTitle == '发布公告'){
          notice_add(this.token,this.formLabelAlign.title,this.formLabelAlign.content,this.formLabelAlign.status,this.formLabelAlign.rel_time).then(res=>{
            if(res.data.status){
              this.$message({
                message:'添加成功',
                type: 'success'
              })
              this.dialogVisible = false
              this.notice_list()
            }else{
              this.$message.error(res.data.msg)
            }
          })
        }
        } else {
          console.log('error submit!!');
          this.submitFormflag = true
          return false;
        }
      });

    },

    // 每页 ${val} 条
    handleSizeChange(val) {
      this.limit = val
      this.notice_list()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.notice_list()
    },
    // 搜索
    search(){
      this.notice_list()
    },
    getNowTime(time){
      let date = new Date(time);
      let year = date.getFullYear();
      let month = date.getMonth()+1;
      let day = date.getDate();
      let hour = date.getHours();
      let minute = date.getMinutes();
      let seconds = date.getSeconds()
      month = month < 10 ? ( '0' + month ) : month
      day = day < 10 ? ( '0' + day ) : day
      hour = hour < 10 ? ( '0' + hour ) : hour
      minute = minute < 10 ? ( '0' + minute ) : minute
      seconds = seconds < 10 ? ( '0' + seconds ) : seconds
      return year+'-'+month+'-'+day+' '+hour+':'+minute+':'+seconds
    },

    // 接口  请求列表
    notice_list(){
      this.loading = true
      notice_list(this.token,this.currentPage,this.limit,this.titleValue).then(res=>{
        if(res.data.status){
          this.tableData = res.data.data.data
          this.total = res.data.data.count
          this.tableData.forEach(item=>{
            item.rel_time_text = this.getNowTime(item.rel_time*1000)
          })
          let timer = setTimeout(()=>{
            this.loading = false
            clearTimeout(timer)
          },400)
        }else{
          if(res.data.msg =="token失效,请重新进行登录"){
            this.$router.push("/login");
          }
          let timer = setTimeout(()=>{
            this.loading = false
            this.$message.error('错误，请刷新');
          },5000)
        }
      })
    },
  },
  created() {
    this.notice_list()
  },
}
</script>

<style scoped>
/deep/.header{
  background: white!important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
  align-items: center;
}
.header .span{
  font-size: initial;
}
.top-input{
  width: 150px;
  margin-right: 20px;
}
/deep/.el-table th.el-table__cell>.cell{
  text-align: center;
}
/deep/.el-table .cell.el-tooltip{
  text-align: center;
}
/deep/.el-table--border .el-table__cell:first-child .cell{
  text-align: center;
}
/deep/.el-table--enable-row-transition .el-table__body td.el-table__cell{
  text-align: center;
}
</style>
